package com.asimplefox.serurity;

import com.asimplefox.entity.Role;
import com.asimplefox.entity.User;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author github.kloping
 */
@Data
public class UserRoleDetails implements UserDetails {

    @JsonIgnore
    private static final SimpleDateFormat SF_0 = new SimpleDateFormat("yyyy-MM-dd");
    @JsonIgnore
    private List<Role> roleList;
    private String username;
    private String password;
    private List<String> roles = new ArrayList<>();
    private User user;

    private Boolean vipd = false;
    private String vip = "";

    public UserRoleDetails(String username, User user, List<Role> roles) {
        this.username = username;
        this.password = user.getPwd();
        this.user = user;
        for (Role role : roles) {
            this.roles.add(role.getUserRole());
        }
        roleList = roles;
    }

    @Override
    @JsonIgnore
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorities = new ArrayList<>();
        roles.stream().map(role -> (GrantedAuthority) () -> role).forEach(authorities::add);
        return authorities;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    public void test() {
        vipd = false;
        for (Role role : roleList) {
            if (role.getUserRole().equalsIgnoreCase(TokenManager.VIP)) {
                vipd = true;
                vip = SF_0.format(role.getTimestamp());
            }
        }
    }
}
